package com.ruoyi.anchor.service;

import cn.hutool.core.lang.Snowflake;
import com.ruoyi.anchor.domain.LiveCart;
import com.ruoyi.anchor.mapper.LiveCartMapper;
import com.ruoyi.base.domain.Store;
import com.ruoyi.base.mapper.StoreMapper;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class LiveCartService {

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private LiveCartMapper liveCartMapper;

    @Autowired
    private Snowflake snowflake;

    @Transactional(transactionManager = "transactionManager", rollbackFor = Exception.class)
    public void saveLiveCart(LiveCart cart) {
        // 出库  批次
        Store store = storeMapper.selectById(cart.getStoreId()); // 1
        // 出库和入库 , 主键、数量、出入库、时间 不一样
        store.setStoreId(snowflake.nextIdStr());
        store.setQuantity(cart.getQuantity());
        store.setInventoryCategory("出库");
        store.setCreateTime(DateUtils.getNowDate());
        storeMapper.insert(store); // 2
        // 创建小黄车
        liveCartMapper.insert(cart); // 3
        // 确认库存, 库存 < 0 回滚
        Store storeCurrent = new Store();
        storeCurrent.setStoreCode(store.getStoreCode());
        storeCurrent.setProductName(store.getProductName());

        int count = storeMapper.selectCountCurrentByCodeAndName(storeCurrent); // 4
        if (count < 0) {
            throw new RuntimeException("库存不足");
        }

    }
}
